﻿using System;
using System.IO;
using System.Text;
using System.Diagnostics;

namespace NewProcessGuarder.core
{
    internal class Logger : ILogger
    {

        protected string _logPath = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName) + ".log";
        public string LogPath
        {
            get { return _logPath; }
            set { if (_logPath != value) _logPath = value; }
        }

        public void AppendLine(string line)
        {
            //需要清理？
            if (NeedClear()) ClearLog();

            if (String.IsNullOrEmpty(line)) return;
            FileMode fmode = File.Exists(LogPath) ? FileMode.Append : FileMode.Create;
            using (FileStream logFile = new FileStream(LogPath, fmode, FileAccess.Write, FileShare.ReadWrite))
            {
                char[] charData;
                byte[] byData;
                try
                {
                    charData = (TimeStick.ToString() + "\t" + line + "\r\n").ToCharArray();
                    byData = new byte[charData.Length];
                    byData = Encoding.Default.GetBytes(charData);
                    logFile.Seek(0, SeekOrigin.Current);
                    logFile.Write(byData, 0, byData.Length);
                }
                catch (Exception ex)
                {
                    throw new Exception("写日志文件出错，错误消息： " + ex.Message);
                }
            }
        }

        public DateTime TimeStick { get { return DateTime.Now; } }
        private int maxLine;
        public int MaxLine
        {
            get { return maxLine; }
            set { maxLine = value; }
        }

        public void ClearLog()
        {
            if (maxLine == 0)
            {
                File.Delete(LogPath);
            }
            else
            {
                StringBuilder fileLine = new StringBuilder();

                using (StreamReader sr = new StreamReader(LogPath))
                {
                    int i = 0;
                    while (sr.Peek() > -1)
                    {
                        if (i > maxLine)
                            fileLine.AppendLine(sr.ReadLine());
                        i++;
                    }
                }
                using (StreamWriter sw = new StreamWriter(LogPath))
                {
                    sw.Write(fileLine.ToString());
                }
            }
        }

        public bool NeedClear()
        {
            using (StreamReader sr = new StreamReader(LogPath))
            {
                int c = sr.ReadToEnd().Split('\n').Length;
                return c > maxLine;
            }
        }
    }
}
